package com.example.runningman.fragment;

import android.accounts.Account;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.runningman.bean.Remark;
import com.example.runningman.bean.Steps;
import com.example.runningman.dao.StepsDao;
import com.example.runningman.database.BaiduPointsDatebase;
import com.example.runningman.run.DynamicDemo;
import com.example.runningman.R;
import com.example.runningman.run.PointActivity;
import com.example.runningman.util.SPUtil;
import com.example.runningman.view.QMAutoTestDialogBuilder;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.qmuiteam.qmui.util.QMUIKeyboardHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import static android.content.Context.SENSOR_SERVICE;

/**
 * A simple {@link Fragment} subclass.
 *
 */
public class BlankFragment extends BaseFragment implements View.OnClickListener,SensorEventListener{
    private BarChart barChart;
    private YAxis leftAxis;             //左侧Y轴
    private YAxis rightAxis;            //右侧Y轴
    TextView steps11;
    private XAxis xAxis;                //X轴
    private Legend legend;              //图例
    private LimitLine limitLine;
    TextView mubiao;
    SensorManager mSensorManager;//管理器实例
    Sensor stepCounter;//传感器
    float mSteps = 0;//步数
    StepsDao stepsDao;
    BaiduPointsDatebase baiduPointsDatebase ;
    Button dyn;
    Button bushu;
    List<Steps> list=new ArrayList<>();
    public BlankFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_blank, container, false);
        // Inflate the layout for this fragment

        return view;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dyn=getActivity().findViewById(R.id.dyn);
        steps11 = (TextView)getActivity().findViewById(R.id.steps11);
        barChart=getActivity().findViewById(R.id.barchart);
        dyn.setOnClickListener(this::onClick);
        List<Integer> listData=new ArrayList<>();
        baiduPointsDatebase = BaiduPointsDatebase.getInstance(getActivity());
        stepsDao=baiduPointsDatebase.StepsDao();
        list=stepsDao.selectAllSteps();
        bushu=getActivity().findViewById(R.id.bushu);
        mhandler=new Mhandler();
        initBarChart(barChart);
        showBarChart(list,"步数表",getResources().getColor(R.color.blue));
        barChart.setOnClickListener(this::onClick);

        // 获取SensorManager管理器实例
        mSensorManager = (SensorManager)getActivity().getSystemService(SENSOR_SERVICE);

        // getSensorList用于列出设备支持的所有sensor列表
        List<Sensor> sensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL);
        Log.i("yyy","Sensor size:"+sensorList.size());
        for (Sensor sensor : sensorList) {
            Log.i("yyy","Supported Sensor: "+sensor.getName());
        }
        mubiao=getActivity().findViewById(R.id.time1);
        mubiao.setOnClickListener(this::onClick);
        bushu.setOnClickListener(this::onClick);

        // 获取计步器sensor
        stepCounter = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
        if(stepCounter != null){
            // 如果sensor找到，则注册监听器
            mSensorManager.registerListener(this,stepCounter,1000000);
        }
        else{
            Log.e("yyy","no step counter sensor found");
        }

    }
    Mhandler mhandler;
    private  class Mhandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){
                String ReturnMessage = (String) msg.obj;
                Log.i("获取的返回信息",ReturnMessage);
                ReturnMessage=ReturnMessage.substring(0,ReturnMessage.indexOf("."));
                steps11.setText(ReturnMessage);

                /***
                 * 在此处可以通过获取到的Msg值来判断
                 * 给出用户提示注册成功 与否，以及判断是否用户名已经存在
                 */

            }
        }
    }
    long i=0;
    @SuppressLint("SetTextI18n")
    @Override
    public void onSensorChanged(SensorEvent event) {
        mSteps = event.values[0];



        if((int)mSteps>(int)list.get(list.size()-1).getStep()){
            int i=(int)mSteps-(int)list.get(list.size()-1).getStep();
            mSteps=i;
        }





        if(SPUtil.getInstance(getActivity()).getBoolean("daychange",false)){
            i=SPUtil.getInstance(getActivity()).getLong("total", 0);
            if(mSteps>=5000){

                int x=SPUtil.getInstance(getActivity()).getInt("day", 0);
                x++;
                SPUtil.getInstance(getActivity()).putInt("day", x);
            }
            SPUtil.getInstance(getActivity()).putBoolean("daychange",false);
        }else {

        }
        SPUtil.getInstance(getActivity()).putLong("total", i+(long)mSteps);


        mhandler.obtainMessage(1, mSteps+"").sendToTarget();


        Log.e("yyy","no step counter sensor foundddddddd"+mSteps);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }
    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.dyn:

                intent = new Intent(getActivity(), DynamicDemo.class);
                startActivity(intent);
                break;

            case R.id.time1:
                QMAutoTestDialogBuilder autoTestDialogBuilder = (QMAutoTestDialogBuilder) new QMAutoTestDialogBuilder(getActivity());
                autoTestDialogBuilder.addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                        .addAction("确定", new QMUIDialogAction.ActionListener() {
                            @SuppressLint("SetTextI18n")
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {


                                mubiao.setText("目标步数:"+autoTestDialogBuilder.getEditText().getText().toString());
                                dialog.dismiss();
                            }
                        });
                autoTestDialogBuilder.show();
                QMUIKeyboardHelper.showKeyboard(autoTestDialogBuilder.getEditText(), true);
                break;
            case R.id.bushu:
                 intent = new Intent(getActivity(), PointActivity.class);
                 startActivity(intent);
                break;
            default:
                break;
        }
    }
    /**
     * 初始化BarChart图表
     */
    private void initBarChart(BarChart barChart) {
        /***图表设置***/
        //背景颜色

        //不显示图表网格
        barChart.setDrawGridBackground(true);
        //背景阴影
        barChart.setDrawBarShadow(false);
        barChart.setHighlightFullBarEnabled(false);
        //显示边框
        barChart.setDrawBorders(true);
        //设置动画效果
        barChart.animateXY(500,500);
        barChart.setDrawBorders(false);


        Description description = new Description();
        description.setEnabled(false);
        barChart.setDescription(description);




        /***XY轴的设置***/
        //X轴设置显示位置在底部
        xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisMinimum(0f);
        xAxis.setGranularity(1f);

        leftAxis = barChart.getAxisLeft();
        rightAxis = barChart.getAxisRight();
        //保证Y轴从0开始，不然会上移一点
        leftAxis.setAxisMinimum(0f);
        rightAxis.setAxisMinimum(0f);
        xAxis.setDrawAxisLine(false);
        leftAxis.setDrawAxisLine(false);
        rightAxis.setDrawAxisLine(false);
        xAxis.setDrawGridLines(false);
        //右侧Y轴网格线设置为虚线
        rightAxis.enableGridDashedLine(10f, 10f, 0f);
        /***折线图例 标签 设置***/
        legend = barChart.getLegend();
        legend.setForm(Legend.LegendForm.LINE);
        legend.setTextSize(11f);
        //显示位置
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        //是否绘制在图表里面
        legend.setDrawInside(false);
    }
    public void showBarChart(List<Steps> list, String name, int color) {

        //for (int i = 0; i < dateValueList.size(); i++) {
            /**
             * 此处还可传入Drawable对象 BarEntry(float x, float y, Drawable icon)
             * 即可设置柱状图顶部的 icon展示
             */
           // int count=20;
            ArrayList<BarEntry> mValues = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        Calendar c = Calendar.getInstance();

            for(int i=1;i<list.size();i++){
                if(list.get(i-1).getTime()==0){
                    continue;
                }
                if(list.size()<9){
                    Date date = new Date(list.get(i).getTime());
                    c.setTime(date);
                    c.add(Calendar.DAY_OF_MONTH, -1);
                    Date yesterday = c.getTime();//这是昨天
                    if(list.get(i).getStep()>list.get(i-1).getStep()){



                        mValues.add(new BarEntry(i, list.get(i).getStep()-list.get(i-1).getStep(),sdf.format(yesterday)));
                    }else {

                        mValues.add(new BarEntry(i, list.get(i).getStep(),sdf.format(yesterday)));
                    }

                }else {
                    Date date = new Date(list.get(list.size()-8+i).getTime());
                    c.setTime(date);
                    c.add(Calendar.DAY_OF_MONTH, -1);
                    Date yesterday = c.getTime();//这是昨天
                    if(list.get(list.size()-8+i).getStep()>list.get(list.size()-9+i).getStep()){
                        mValues.add(new BarEntry(i, list.get(list.size()-8+i).getStep()-list.get(list.size()-9+i).getStep(),sdf.format(yesterday)));
                    }
                    else {
                        mValues.add(new BarEntry(i, list.get(list.size()-8+i).getStep(),sdf.format(yesterday)));

                    }
                }

                if(i+1==8){
                    break;
                }
            }
        Log.e("sssss", mValues.size()+"");
            if(mValues.size()>1){


            IAxisValueFormatter formatter = new IAxisValueFormatter() {

                @Override
                public synchronized  String getFormattedValue(float value, AxisBase axis) {
                    if(value-1>=0){
                        return mValues.get((int)value-1).getData().toString();
                    }
                    Log.e("sssss", value+"");
                    return  "0";
                }

                @Override
                public int getDecimalDigits() {
                    return 0;
                }

            };
            // 引用标签
            xAxis.setValueFormatter(formatter);
            xAxis = barChart.getXAxis();


            }

           // count++;

            //entries.add(barEntry);
      //  }
        // 每一个BarDataSet代表一类柱状图
        BarDataSet barDataSet = new BarDataSet(mValues, name);
        initBarDataSet(barDataSet, color);

        BarData data = new BarData(barDataSet);
        barChart.setData(data);
    }
    /**
     * 柱状图始化设置 一个BarDataSet 代表一列柱状图
     *
     * @param barDataSet 柱状图
     * @param color      柱状图颜色
     */
    private void initBarDataSet(BarDataSet barDataSet, int color) {
        barDataSet.setColor(color);
        barDataSet.setFormLineWidth(1f);
        barDataSet.setFormSize(15.f);
        //不显示柱状图顶部值
        barDataSet.setDrawValues(false);
//        barDataSet.setValueTextSize(10f);
//        barDataSet.setValueTextColor(color);
    }
    public void toadst(){
        Toast.makeText(getActivity(), "存在敏感词汇", Toast.LENGTH_SHORT).show();
    }
}
